# coding=utf-8
import json

import time

from django.db import transaction

from worldcup.apps.userModel.models import TravelEvent, Travel
from worldcup.commons import SqlExecutor
from worldcup.commons.CommonResult import rest, CommonResult


@transaction.atomic
@rest
def support(request):
	"""
    点赞
    """
	request_params = json.loads(request.body)
	openid = request_params["supportedOpenid"]  # 被顶人id
	support_openid = request_params["openid"]  # 顶人id
	# 查询是否录入信息
	travel_num = Travel.objects.filter(openid=openid).count()
	if travel_num == 0:
		return CommonResult(-1, "您还没有录入行程信息!请点击右上角\"个人\"录入。")
	# 查询次数
	travel_events = TravelEvent.objects.filter(openid=support_openid, event=1, created_at__gte=int(time.mktime(
		time.strptime(time.strftime('%Y-%m-%d 00:00:00', time.localtime(time.time())), '%Y-%m-%d %H:%M:%S')))).all()
	if len(travel_events) >= 6:
		return CommonResult(-1, "您今天已经顶了6次，明天再来顶吧！")
	for travel_event in travel_events:
		if travel_event.rec_openid == openid:
			return CommonResult(-1, "您今天已经顶过她/他了，明天再来顶吧！")
	# 插入
	travel_event = TravelEvent(openid=support_openid, rec_openid=openid, event=1, created_at=int(time.time()), status=1)
	travel_event.save()
	# 数量冗余记录
	SqlExecutor.executeUpdate("update userModel_user set support_num = support_num + 1 "
							  "where openid = '%s'" % openid)
	return CommonResult(0, "success")


@rest
def date(request):
	"""
    约伴
    """
	request_params = json.loads(request.body)
	openid = request_params["openid"]  # 约人id
	dated_openid = request_params["datedOpenid"]  # 被约人id
	# 查询
	count = TravelEvent.objects.filter(openid=openid, rec_openid=dated_openid, event=3).count()
	if count > 0:
		return CommonResult(-1, "您已经约过他/她了")
	travel_event = TravelEvent(openid=openid, rec_openid=dated_openid, event=3, result=3, created_at=int(time.time()),
							   status=1)
	travel_event.save()
	return CommonResult(0, "success")


@rest
def handle_date(request):
	"""
    处理约伴
    """
	request_params = json.loads(request.body)
	date_id = request_params["dateId"]
	result = request_params["result"]
	travel_event = TravelEvent.objects.filter(id=date_id).get()
	travel_event.result = result;
	travel_event.save()
	return CommonResult(0, "success")


@rest
def get_remain_view_num(request):
	"""
    获取用户当天剩余查看次数
    """
	# openid = request.GET["openid"]
	# num = TravelEvent.objects.values("rec_openid").filter(openid=openid, event=2, created_at__gte=int(time.mktime(
	# 	time.strptime(time.strftime('%Y-%m-%d 00:00:00', time.localtime(time.time())), '%Y-%m-%d %H:%M:%S')))
	# 													  ).distinct().count()
	# remain_view_num = 6 - num
	# if remain_view_num < 0:
	# 	remain_view_num = 0
	# 取消限制
	remain_view_num = 6
	return CommonResult(0, remain_view_num)
